perf: reduce search and document latency#718
Conversation
Add progressive search, bounded document loading, safe owner caches, and indexed persistence paths while preserving existing JSON and detail contracts. Includes Docker replay evidence and targeted offline verification.
Preserve title-vocabulary privacy during backfill, keep trigger ACLs hardened, prevent medication seed flights from aborting themselves, and make shared-dependency worktrees use the supported Webpack fallback. Refresh focused UI and schema coverage.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (18)
🚧 Files skipped from review as they are similar to previous changes (15)
📝 WalkthroughWalkthroughThis PR adds bundle and fixture safeguards, streamed universal search, server-seeded document viewing, abort-aware retrieval and caching, fixture-aware API caching, atomic rate limits, ranking modules, database cleanup/title indexing, and extensive regression and operational coverage. ChangesPerformance and application-flow remediation
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
CI triageCI failed on this PR. Automated classification of the 2 failed job(s):
Compared with main CI run #2769 (success). Classification is evidence routing, not permission to ignore a failure. Exact quarantined Playwright identities remain governed by the flake ledger. |
There was a problem hiding this comment.
Actionable comments posted: 9
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/components/DocumentViewer.tsx`:
- Around line 1936-1942: Update the download flow in DocumentViewer so every
overview/mobile download action invokes openSourceDownload() and revalidates the
signed URL through getCachedSignedUrl() rather than using the stored URL
directly. Remove or bypass direct uses of the cached download URL for click
handling, while preserving the existing anchor download behavior after a fresh
payload is obtained.
In `@src/lib/document-detail.ts`:
- Around line 400-409: Update the document_chunks query in the chunk retrieval
flow, including the related query at the alternate location, to apply the
committed-generation predicate before range or limit pagination. Ensure stale
generations cannot consume the selected window, while preserving the existing
selectedChunk filtering and chunk ordering behavior.
In `@src/lib/document-enrichment.ts`:
- Around line 801-806: The metadata query results in the enrichment flow must
not ignore failures: after awaiting Promise.all for labelsQuery and
summariesQuery, inspect labelsResult.error and summariesResult.error and
propagate any error before constructing or caching rows. Preserve normal
processing when both queries succeed, including abort errors rather than
converting them into empty metadata.
In `@src/lib/rag.ts`:
- Around line 1296-1297: Update the non-lexical search flow around
requestClassifierVerdict() to race its per-request await against opts.signal,
allowing cancellation to return without waiting for classifier completion while
leaving the shared in-flight promise untouched. Preserve the existing classifier
result handling when the signal has not been canceled.
In `@src/lib/registry-seed.ts`:
- Around line 170-171: Update the invalidateOwnerCatalogueCache call in the
seeding flow to pass preserveSignal: options.signal, ensuring the active seeding
catalogue flight is not aborted before throwIfAborted checks it.
In `@supabase/migrations/20260717131000_public_title_corrector.sql`:
- Around line 95-130: Update the title-correction candidate query in
supabase/migrations/20260717131000_public_title_corrector.sql (lines 95-130) so
alias matches emit their canonical term while retaining the alias-match
similarity for ranking; mirror this implementation in supabase/schema.sql (lines
5101-5136). Add a test in tests/supabase-schema.test.ts (lines 1256-1262)
asserting an exact typo alias resolves to its canonical term, then regenerate
the function hash in supabase/drift-manifest.json (line 6433).
In `@supabase/schema.sql`:
- Around line 7853-7859: Update the quota function in supabase/schema.sql so the
limit and reset timestamp are tracked from the policy that produces
v_min_remaining, then return those values instead of p_summary_limit and the
last policy’s v_reset_at. Add coverage in tests/supabase-schema.test.ts for
differing limits and windows, asserting a coherent success tuple. Regenerate the
function hash in supabase/drift-manifest.json at line 6409.
In `@tests/client-performance-boundaries.test.ts`:
- Line 44: Update the PDF.js import assertion in the relevant
performance-boundary test to reject both named/default imports and
side-effect-only imports from "pdfjs-dist", while preserving the existing
allowance for type-only imports.
In `@tests/proxy-session-refresh.test.ts`:
- Line 15: Remove the duplicated createServerClient property from its own mock
initializer in the test setup, leaving a single createServerClient declaration
that returns the intended client shape and compiles correctly.
🪄 Autofix (Beta)
❌ Autofix failed (check again to retry)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 1d9b6ce2-6092-4008-a7ed-aeec69332d2d
📒 Files selected for processing (90)
bundle-budget.jsondocs/branch-review-ledger.mddocs/operator-apply-performance-latency-remediation.mdscripts/check-bundle-budget.mjsscripts/dev-free-port.mjssrc/app/api/answer/stream/route.tssrc/app/api/differentials/[slug]/route.tssrc/app/api/differentials/presentations/[slug]/route.tssrc/app/api/differentials/route.tssrc/app/api/documents/[id]/labels/route.tssrc/app/api/documents/[id]/route.tssrc/app/api/medications/[slug]/route.tssrc/app/api/medications/route.tssrc/app/api/registry/records/[slug]/route.tssrc/app/api/registry/records/route.tssrc/app/api/search/universal/route.tssrc/app/documents/[id]/page.tsxsrc/components/ClinicalDashboard.tsxsrc/components/DocumentViewer.tsxsrc/components/clinical-dashboard/differentials-home.tsxsrc/components/clinical-dashboard/use-universal-search.tssrc/components/document-viewer-lazy.tsxsrc/components/forms/form-detail-page.tsxsrc/components/forms/forms-search-results-page.tsxsrc/components/services/service-detail-page.tsxsrc/components/services/services-navigator-page.tsxsrc/lib/answer-client-payload.tssrc/lib/answer-response.tssrc/lib/api-rate-limit.tssrc/lib/clinical-safety.tssrc/lib/corpus-grounding.tssrc/lib/cross-mode-links.tssrc/lib/deep-memory.tssrc/lib/differential-search-composition.tssrc/lib/differentials.tssrc/lib/document-detail-contract.tssrc/lib/document-detail.tssrc/lib/document-enrichment.tssrc/lib/fixture-response-cache.tssrc/lib/form-catalog.tssrc/lib/form-ranker.tssrc/lib/forms.tssrc/lib/http.tssrc/lib/medication-seed.tssrc/lib/owner-catalogue-cache.tssrc/lib/rag-cache.tssrc/lib/rag-candidate-sources.tssrc/lib/rag-retrieval-variants.tssrc/lib/rag.tssrc/lib/registry-seed.tssrc/lib/search-command-surface.tssrc/lib/service-ranker.tssrc/lib/services.tssrc/lib/supabase/auth.tssrc/lib/supabase/database.types.tssrc/lib/types.tssrc/lib/universal-search-stream.tssrc/lib/universal-search.tssrc/proxy.tssupabase/drift-manifest.jsonsupabase/migrations/20260717130000_registry_projection_cleanup.sqlsupabase/migrations/20260717131000_public_title_corrector.sqlsupabase/migrations/20260717132000_atomic_summary_rate_limits.sqlsupabase/schema.sqltests/answer-client-payload.test.tstests/api-rate-limit-fallback.test.tstests/api-validation-contract.test.tstests/bundle-budget.test.tstests/client-performance-boundaries.test.tstests/differentials-route.test.tstests/document-detail-performance.test.tstests/document-enrichment-visual-counts.test.tstests/fixture-response-cache.test.tstests/medications-route.test.tstests/owner-catalogue-cache.test.tstests/private-access-routes.test.tstests/private-error-cache.test.tstests/private-rag-access.test.tstests/proxy-session-refresh.test.tstests/rag-abort-signal.test.tstests/rag-cache-invalidation.test.tstests/rag-variant-early-exit.test.tstests/registry-records-route.test.tstests/supabase-schema.test.tstests/test-runner-safety.test.tstests/ui-smoke.spec.tstests/ui-universal-search.spec.tstests/universal-search-stream.test.tstests/universal-search.test.tstests/use-universal-search-stream.dom.test.tsx
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@supabase/migrations/20260717173000_reassert_supabase_admin_default_privileges.sql`:
- Around line 52-109: Update the privilege entries produced by the exploded CTE
to retain aclexplode’s is_grantable value, then make the v_safe validation
reject any grantable privilege, including otherwise allow-listed service_role
privileges. Ensure ordinary non-grantable entries continue matching the existing
allow-list checks.
🪄 Autofix (Beta)
❌ Autofix failed (check again to retry)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 46fdacd7-c028-4adb-963d-1d4a89401c10
📒 Files selected for processing (17)
docs/branch-review-ledger.mddocs/operator-apply-performance-latency-remediation.mddocs/process-hardening.mdsrc/app/api/documents/[id]/route.tssrc/components/ClinicalDashboard.tsxsrc/components/DocumentViewer.tsxsrc/lib/supabase/database.types.tssrc/lib/types.tssupabase/drift-manifest.jsonsupabase/migrations/20260717170000_registry_projection_cleanup.sqlsupabase/migrations/20260717171000_public_title_corrector.sqlsupabase/migrations/20260717172000_atomic_summary_rate_limits.sqlsupabase/migrations/20260717173000_reassert_supabase_admin_default_privileges.sqlsupabase/schema.sqltests/private-access-routes.test.tstests/supabase-schema.test.tstests/ui-smoke.spec.ts
🚧 Files skipped from review as they are similar to previous changes (11)
- src/lib/types.ts
- docs/operator-apply-performance-latency-remediation.md
- src/lib/supabase/database.types.ts
- src/app/api/documents/[id]/route.ts
- tests/supabase-schema.test.ts
- supabase/drift-manifest.json
- tests/ui-smoke.spec.ts
- docs/branch-review-ledger.md
- src/components/ClinicalDashboard.tsx
- supabase/schema.sql
- src/components/DocumentViewer.tsx
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. The agent ran but didn't make any changes. The issues may already be fixed or require manual intervention. |
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found. |
Summary
Verification
npm run verify:pr-localVerification not run to completion on the final head: two early attempts exposed formatting and lint issues that were fixed; repository instructions then prohibited a third repeat. Equivalent final components passed individually: exact TypeScript, scoped ESLint/Prettier, focused tests, production build, bundle budget, and offline RAG. Hosted exact-head CI remains authoritative.
npm run verify:uiwhen UI, routing, styling, browser behavior, reduced-motion, or forced-colors behavior changedUI verification not run: full-suite completion was not achieved locally; the isolated production build completed, but the broad Chromium run exceeded the 20-minute host window. Focused exact-head Chromium passed dashboard request deferral and NDJSON universal search; the viewer trace passed hydration, zero redundant detail/setup requests, one preview signature, and zero pre-click download signatures before a stale button-label assertion. The selector is corrected to the accessible
Downloadcontrol and the required hosted critical-UI lane must pass before merge.npm run verify:releasebefore release or handoff confidence claimsVerification not run: release is broader than this PR and includes provider-gated work.
npm run eval:retrieval:quality(must stay 36/36) when retrieval, ranking, selection, chunking, or scoring behavior changed — CI cannot run it (needs live keys), so run it locally and paste the summary. A metadata/governance-weighting change once buried correct docs (recall 1.0→0.76) and only this eval caught it.Verification not run: this live evaluation requires provider credentials and OpenAI usage was not authorized. Provider-free
npm run eval:rag:offlinepassed 36 fixtures / 21 suites / 291 tests.npm run eval:rag -- --limit 15+npm run eval:quality -- --rag-onlywhen answer generation, the synthesis prompt, or answer post-processing changed (grounded-supported must not drop; citation-failure 0)Verification not run: provider-backed generation was not authorized; answer source changes are payload bounding only and offline RAG passed.
npm run check:production-readinesswhen clinical workflow, privacy, environment, Supabase, source governance, or deployment behavior changedOffline/static
--cipath passed with only expected warnings for intentionally absent provider credentials.npm run check:deployment-readinesswhen deployment startup, hosting, or rollout behavior changedVerification not run: no deployment or hosting configuration changed.
Additional exact results:
EXPLAIN (FORMAT JSON)selecteddocument_chunks_search_idx,document_table_facts_title_row_param_trgm_idx, anddocument_chunks_embedding_hnsw_idx.git diff --checkpassed on the final tree.Risk and rollout
EXPLAINonly. No live DDL, migration apply, rate-limit RPC, data write, OpenAI call, deployment, or production mutation.Clinical Governance Preflight
Clinical KB Database(sjrfecxgysukkwxsowpy)Notes
docs/operator-apply-performance-latency-remediation.md; pre-create the documents expression index concurrently during an explicitly authorized production rollout.C:\Dev\Apps\Database\worktrees\performance-latency-remediation-20260717with Node 24/npm 11 dependencies shared from an existing repository worktree; no package install or lockfile change occurred.Summary by CodeRabbit
New Features
Bug Fixes
Performance
Documentation